'use strict';
const extend = require('extend2');
const configCache = {};

// 模拟app，为了获取config
function getMockApp() {
  const npmConf = require(`${process.ROOT}/package.json`);
  return {
    name: npmConf.name,
  };
}

// 根据环境读取配置
function getConfigByEnv(env = 'default') {
  if (configCache[env]) return configCache[env];

  const app = getMockApp();
  configCache[env] = require(`${process.ROOT}/config/config.${env}.js`)(app);
  return configCache[env];
}

// 获取实际配置
function getAllConfig() {
  const defaultConf = getConfigByEnv('default');

  const env = 'local';
  const envConf = getConfigByEnv(env);

  const conf = extend(true, defaultConf, envConf);
  return conf;
}

// 获取配置
exports.getConfig = function(str = '') {
  const allConfig = getAllConfig();
  if (!str) return allConfig;
  // 配置文件中获取
  const keys = str.split('.');
  const getVal = function(obj, key) { return obj[key]; };

  let config = allConfig;
  keys.forEach(key => {
    if (config) config = getVal(config, key);
  });
  return config;
};

